package net.gz01.wallet.web.controller.admin;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import net.gz01.util.ZOMoney;
import net.gz01.wallet.common.*;
import org.apache.commons.lang3.StringUtils;
import org.jxls.common.Context;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

import lombok.extern.slf4j.Slf4j;
import net.gz01.util.ZODate;
import net.gz01.util.ZOExcel;
import net.gz01.util.ZOLog;
import net.gz01.wallet.message.AccountBalanceChangeResp;
import net.gz01.wallet.web.config.SystemConfig;
import net.gz01.wallet.web.config.SystemEnum;
import net.gz01.wallet.web.config.SystemEnum.BizType;
import net.gz01.wallet.web.config.SystemEnum.OrderStatus;
import net.gz01.wallet.web.config.SystemEnum.Resp;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.model.Account;
import net.gz01.wallet.web.model.Channel;
import net.gz01.wallet.web.model.Dictionary;
import net.gz01.wallet.web.model.Merch;
import net.gz01.wallet.web.model.MerchUser;
import net.gz01.wallet.web.model.TradeOrder;
import net.gz01.wallet.web.model.YouliAccount;
import net.gz01.wallet.web.service.AccountService;

@Slf4j
public class PayOrderController extends BaseController {
	private AccountService accountService = Duang.duang(AccountService.class);

	public void search() {
		List<Dictionary> dictionaryList = Dictionary.dao.selectBizType();
		List<Dictionary> bizTypeList = new ArrayList<>();

		for(Dictionary dictionary : dictionaryList){
			if(BizType.DF_Personal.getValue().equals(dictionary.getCode()) ||
				BizType.DF_Company.getValue().equals(dictionary.getCode()) ||
			BizType.Withdraw_Personal.getValue().equals(dictionary.getCode()) ||
			BizType.Withdraw_Company.getValue().equals(dictionary.getCode()) ||
			BizType.TransferOut.getValue().equals(dictionary.getCode())){
				bizTypeList.add(dictionary);
			}
		}
		setAttr("bizTypeList", bizTypeList);
		setAttr("orderStatusList", Dictionary.dao.selectOrderStatus());
		setAttr("amtLimit", Dictionary.dao.getAmtLimit());
		render("trade/payOrderList.html");
	}

	public void listJson() {
		ZOSearchCondition sc = super.getSearchCondition();
		String myBizType = sc.getStr("bizTypex");
		if(myBizType!=null && myBizType.length() > 0) {
			String[] bizTypes = myBizType.split(";");
			int tt = 2;
			for(int i = 0; i < bizTypes.length; i++){
				if(StringUtils.isNotEmpty(bizTypes[i])){
					if(i == 0) {
						sc.setParameter("bizType", bizTypes[i]);
					}else {
						sc.setParameter("bizType" + tt, bizTypes[i]);
						tt++;
					}
				}
			}
		}else {
			sc.setParameter("bizType", BizType.DF_Personal.getValue());
			sc.setParameter("bizType2", BizType.DF_Company.getValue());
			sc.setParameter("bizType3", BizType.Withdraw_Personal.getValue());
			sc.setParameter("bizType4", BizType.Withdraw_Company.getValue());
			sc.setParameter("bizType5", BizType.TransferOut.getValue());
		}
		Page<TradeOrder> pageResult = TradeOrder.dao.search(sc);
		renderJson(new PageRespon(pageResult));
	}

	public void firstReviewPage() {
		TradeOrder item = TradeOrder.dao.findById(getPara("id"));
		setAttr("item", item);
		setAttr("channel", Channel.dao.selectByCode(item.getChannelCode()));
		setAttr("account", Account.dao.select(item.getMerchCode()));
		setAttr("merch", Merch.dao.selectByMerchCode(item.getMerchCode()));
		setAttr("youliAccountList", YouliAccount.dao.selectAll());

		File fileList = new File(SystemEnum.FilePath.Trade.getValue() + item.getOrderNo());
		int num = 0;
		if(fileList!=null && fileList.list()!=null){
			num = fileList.list().length;
		}
		setAttr("fileNum", num);
		setAttr("fileList", fileList.list());

		render("trade/payOrderFirstReview.html");
	}

	public void secondReviewPage() {
		TradeOrder item = TradeOrder.dao.findById(getPara("id"));
		setAttr("item", item);
		setAttr("channel", Channel.dao.selectByCode(item.getChannelCode()));
		setAttr("account", Account.dao.select(item.getMerchCode()));
		setAttr("merch", Merch.dao.selectByMerchCode(item.getMerchCode()));
		File fileList = new File(SystemEnum.FilePath.Trade.getValue() + item.getOrderNo());
		int num = 0;
		if(fileList!=null && fileList.list()!=null){
			num = fileList.list().length;
		}
		setAttr("fileNum", num);
		setAttr("fileList", fileList.list());
		render("trade/payOrderSecondReview.html");
	}

	public void thirdReviewPage() {
		TradeOrder item = TradeOrder.dao.findById(getPara("id"));
		setAttr("item", item);
		setAttr("account", Account.dao.select(item.getMerchCode()));
		setAttr("channel", Channel.dao.selectByCode(item.getChannelCode()));
		setAttr("merch", Merch.dao.selectByMerchCode(item.getMerchCode()));
		File fileList = new File(SystemEnum.FilePath.Trade.getValue() + item.getOrderNo());
		int num = 0;
		if(fileList!=null && fileList.list()!=null){
			num = fileList.list().length;
		}
		setAttr("fileNum", num);
		setAttr("fileList", fileList.list());
		render("trade/payOrderThirdReview.html");
	}

	public void transferOutReviewPage() {
		TradeOrder item = TradeOrder.dao.findById(getPara("id"));
		setAttr("item", item);
		setAttr("account", Account.dao.select(item.getMerchCode()));
		setAttr("channel", Channel.dao.selectByCode(item.getChannelCode()));
		setAttr("merch", Merch.dao.selectByMerchCode(item.getMerchCode()));
		File fileList = new File(SystemEnum.FilePath.Trade.getValue() + item.getOrderNo());
		int num = 0;
		if(fileList!=null && fileList.list()!=null){
			num = fileList.list().length;
		}
		setAttr("fileNum", num);
		setAttr("fileList", fileList.list());
		render("trade/payOrderTransferOut.html");
	}

	public void transferOutUploadData(){
		TradeOrder item = TradeOrder.dao.findById(getPara("id"));
		setAttr("item", item);
		setAttr("account", Account.dao.select(item.getMerchCode()));
		setAttr("channel", Channel.dao.selectByCode(item.getChannelCode()));
		setAttr("merch", Merch.dao.selectByMerchCode(item.getMerchCode()));
		File fileList = new File(SystemEnum.FilePath.Trade.getValue() + item.getOrderNo());
		int num = 0;
		if(fileList!=null && fileList.list()!=null){
			num = fileList.list().length;
		}
		setAttr("fileNum", num);
		setAttr("fileList", fileList.list());
		render("trade/transferOutUploadData.html");
	}


	/**
	 * 付款类订单审核通过后， 统一为 待打款 这样的状态。
	 *
	 * 提现(付款)一审
	 */
	@Before(Tx.class)
	public void firstReview() {
		TradeOrder item = TradeOrder.dao.findById(getPara("id"));
		String reviewResult = getPara("reviewResult");
		boolean firstReviewOrderStatus = OrderStatus.FirstReview.getValue().equals(item.getOrderStatus())
				|| OrderStatus.SecondReviewFail.getValue().equals(item.getOrderStatus())
				|| OrderStatus.ThirdReviewFail.getValue().equals(item.getOrderStatus());
		if (!firstReviewOrderStatus) {
			renderMsg(2, "订单状态错误,不能进行一审操作!");
			return;
		}

		if ("unPass".equals(reviewResult)) {
			String remark = getPara("remark");
			if (StringUtils.isBlank(remark)) {
				renderMsg(2, "审核不通过的备注信息必须填写!");
				return;
			}
			item.setPurpose(remark);
			item.setRespCode(Resp.Fail.getCode());
			item.setRespMsg(remark);
			item.setOrderStatus(OrderStatus.FirstReviewFail.getValue());
			item.update();
			// 金额加回去...
			AccountBalanceChangeResp resp = accountService.addMoney(item.getMerchCode(), Math.abs(item.getFee()) + Math.abs(item.getAmount()));
			if (!"SUCCESS".equals(resp.getRespCode())) {
				// 严重错误：发送短信告知
				log.error("一审严重错误:" + JSON.toJSON(item) + "------" + "此订单审核失败，回滚金额错误!!");
			}
			renderSuccess("此订单已经审核不通过!");
			return;
		}

		if ("pass".equals(reviewResult)) {
			String purpose = getPara("purpose");
			if (StringUtils.isBlank(purpose)) {
				renderMsg(2, "审核通过的订单用途信息必须填写!");
				return;
			}
			if(!BizType.TransferOut.getValue().equals(item.getBizType())) {
				YouliAccount youliAccount = YouliAccount.dao.findById(getPara("youliAccountId"));
				if (youliAccount == null) {
					renderMsg(2, "友利出账卡信息错误!--->" + getPara("youliAccountId"));
					return;
				}
				item.setOutAccountName(youliAccount.getAccountName());
				item.setOutAccountNo(youliAccount.getAccountNo());
				item.setOutBankName(youliAccount.getBankName());
			}
			item.setPurpose(purpose);
			item.setOrderStatus(OrderStatus.SecondReview.getValue());
			item.setRespCode(Resp.Success.getCode());
			item.setRespMsg("一审通过");
			item.update();
			renderSuccess("一审成功");
		}
	}

	/**
	 * 提现(付款)二审
	 */
	@Before(Tx.class)
	public void secondReview() {
		TradeOrder item = TradeOrder.dao.findById(getPara("id"));
		String reviewResult = getPara("reviewResult");

		if (!OrderStatus.SecondReview.getValue().equals(item.getOrderStatus())) {
			renderMsg(2, "二审--审核状态错误!!!");
			return;
		}

		// 二审不通过
		if (OrderStatus.SecondReview.getValue().equals(item.getOrderStatus()) && reviewResult.equals("unPass")) {
			String remark = getPara("remark");
			if (StringUtils.isBlank(remark)) {
				renderMsg(2, "审核不通过的备注信息必须填写!");
				return;
			}
			if(StrKit.notBlank(item.getPurpose2())) {
				item.setPurpose2(item.getPurpose2() +"\n" + "二审人员在" + ZODate.getDateTime() +"的审核意见是:" + remark);
			} else {
				item.setPurpose2("二审人员在" + ZODate.getDateTime() +"的审核意见是:" + remark);
			}
			item.setRespCode(Resp.Fail.getCode());
			item.setRespMsg(remark);
			item.setOrderStatus(OrderStatus.SecondReviewFail.getValue());
			item.update();

			renderSuccess("此订单已经审核不通过!请通知一审人员继续审核流程!");
			return;
		}

		// 二审通过
		if (OrderStatus.SecondReview.getValue().equals(item.getOrderStatus()) && "pass".equals(reviewResult)) {
			String purpose2 = getPara("purpose2");
			if (StringUtils.isBlank(purpose2)) {
				renderMsg(2, "二审审核通过意见必须填写!");
				return;
			}

			if(StringUtils.isNotEmpty(item.getPurpose2())) {
				item.setPurpose2(item.getPurpose2() + "\n" + "二审人员在" + ZODate.getDateTime() + "的审核意见是:" + purpose2);
			}else {
				item.setPurpose2("二审人员在" + ZODate.getDateTime() + "的审核意见是:" + purpose2);
			}
			String inputAmt = getPara("inputAmt");
			if(StringUtils.isEmpty(inputAmt)){
				renderMsg(2, "审核通过的核实交易金额必填!");
				return;
			}
			if(!ZOMoney.changeY2F(Double.parseDouble(inputAmt)).equals(""+Math.abs(item.getAmount()))){
				renderMsg(2, "核实交易金额和订单交易金额不一致!");
				return;
			}

			// 大于等于300万需要三审
			if (Math.abs(item.getAmount()) >= Dictionary.dao.getAmtLimit()) {
				item.setOrderStatus(OrderStatus.ThirdReview.getValue());
				item.update();
				item.setRespCode(Resp.Success.getCode());
				item.setRespMsg("二审通过");
				renderSuccess("此订单二审通过!");
				return;
			}
			setOrderTransferOut(item, "二审通过");// 设置订单为待打款状态
			renderSuccess("此订单二审通过.");
		}
	}

	/**
	 * 提现(付款)三审
	 */
	@Before(Tx.class)
	public void thirdReview() {
		TradeOrder item = TradeOrder.dao.findById(getPara("id"));
		String reviewResult = getPara("reviewResult");

		if (!OrderStatus.ThirdReview.getValue().equals(item.getOrderStatus())) {
			renderMsg(2, "三审--审核状态错误!!!");
			return;
		}

		// 三审不通过
		if (OrderStatus.ThirdReview.getValue().equals(item.getOrderStatus()) && reviewResult.equals("unPass")) {
			String remark = getPara("remark");
			if (StringUtils.isBlank(remark)) {
				renderMsg(2, "审核不通过的备注信息必须填写!");
				return;
			}
			if(StrKit.notBlank(item.getPurpose3())) {
				item.setPurpose3(item.getPurpose3() +"\n" + "三审人员在" + ZODate.getDateTime() +"的审核意见是:" + remark);
			} else {
				item.setPurpose3("三审人员在" + ZODate.getDateTime() +"的审核意见是:" + remark);
			}
			item.setRespCode(Resp.Fail.getCode());
			item.setRespMsg(remark);
			item.setOrderStatus(OrderStatus.ThirdReviewFail.getValue());
			item.update();

			renderSuccess("此订单审核不通过! 请通知一审人员继续审核流程!");
			return;
		}
		// 三审通过
		if (OrderStatus.ThirdReview.getValue().equals(item.getOrderStatus()) && "pass".equals(reviewResult)) {
			String purpose3 = getPara("purpose3");
			if (StringUtils.isBlank(purpose3)) {
				renderMsg(2, "二审审核通过意见必须填写!");
				return;
			}

			String inputAmt = getPara("inputAmt");
			if(StringUtils.isEmpty(inputAmt)){
				renderMsg(2, "审核通过的核实交易金额必填!");
				return;
			}
			if(!ZOMoney.changeY2F(Double.parseDouble(inputAmt)).equals(""+Math.abs(item.getAmount()))){
				renderMsg(2, "核实交易金额和订单交易金额不一致!");
				return;
			}

			if(StringUtils.isNotEmpty(item.getPurpose3())) {
				item.setPurpose3(item.getPurpose3() + "\n" + "三审人员在" + ZODate.getDateTime() + "的审核意见是:" + purpose3);
			}else {
				item.setPurpose3( "三审人员在" + ZODate.getDateTime() + "的审核意见是:" + purpose3);
			}
			setOrderTransferOut(item, "三审通过");// 设置订单为待打款状态
			renderSuccess("此订单三审通过!");
		}
	}

	/*
	 **
	 * 最终打款操作
	 */
	@Before(Tx.class)
	public void toTransferOut() {
		TradeOrder item = TradeOrder.dao.findById(getPara("id"));
		String reviewResult = getPara("reviewResult");

		if (!OrderStatus.WaitTransferOut.getValue().equals(item.getOrderStatus())) {
			renderMsg(2, "订单:" + item.getOrderNo() +"待打款-----审核状态错误!!!只能是 WaitTransferOut");
			return;
		}

		if (!("unPass".equals(reviewResult) || "pass".equals(reviewResult))) {
			renderMsg(2, "订单:" + item.getOrderNo() +"待打款----打款状态错误!!!只能是 pass 和 unPass");
			return;
		}

		// 打款失败.....
		if ("unPass".equals(reviewResult)) {
			String remark = getPara("remark");
			if (StringUtils.isBlank(remark)) {
				renderMsg(2, "订单:" + item.getOrderNo() +"打款失败的原因信息必须填写!");
				return;
			}
			item.setPurpose4(remark);
			item.setRespCode(Resp.Fail.getCode());
			item.setRespMsg(remark);
			item.setOrderStatus(OrderStatus.WaitTransferFail.getValue());
			item.update();
			// 金额加回去...
			AccountBalanceChangeResp resp = accountService.addMoney(item.getMerchCode(),
					Math.abs(item.getFee()) + Math.abs(item.getAmount()));
			if (!"SUCCESS".equals(resp.getRespCode())) {
				// 严重错误：发送短信告知
				log.error("订单:" + item.getOrderNo() +"打款失败严重错误:" + JSON.toJSON(item) + "------" + "此订单审核失败，回滚金额错误!!");
			}
			renderSuccess("订单:" + item.getOrderNo() +"此订单打款失败!");
			return;
		}

		String purpose4 = getPara("purpose4");
		if (StringUtils.isBlank(purpose4)) {
			renderMsg(2, "订单:" + item.getOrderNo() +"打款成功意见必须填写!");
			return;
		}
		item.setPurpose4(purpose4);
		long payAmount = Math.abs(item.getAmount());

		if (BizType.TransferOut.getValue().equals(item.getBizType())) {
			// 收款方钱包余额加钱
			AccountBalanceChangeResp resp = accountService.addMoney(item.getAccountNo(), payAmount);
			if (resp.getRespCode().equals("SUCCESS")) {
				item.setAccountBalance(Long.parseLong(resp.getBalance()));
				item.setOrderStatus(OrderStatus.Success.getValue());
				item.setRespCode(Resp.Success.getCode());
				item.setRespMsg(Resp.Success.getMsg());
				item.setPayTime(ZODate.getDateTime());
				item.setSettleDate(ZODate.getDate());
				item.setOutAccountName(item.getAccountName());
				item.setOutAccountNo(item.getAccountNo());
				renderSuccess("转账成功");

				MerchUser userOut = MerchUser.dao.selectByMerCode(item.getMerchCode());
				if (userOut != null) {
					// 钱包内转账收款方的 短信发送
					WalletSMS.sendSMSSubMenoy(userOut.getUserName(), payAmount, (item.getBalance()));
				}

				// 创建一笔钱包转入账的订单---手续费收取发起转账的， 转入方不收取手续费
				TradeOrder orderIn = new TradeOrder();
				orderIn.createOrderPayIn(item, BizType.TransferIn.getValue());

				MerchUser user = MerchUser.dao.selectByMerCode(item.getAccountNo());
				if (user != null) {
					// 钱包内转账收款方的 短信发送
					WalletSMS.sendSMSAddMenoy(user.getUserName(), payAmount, Long.parseLong(resp.getBalance()));
				}

			} else {
				log.error("运营人员点击了打款成功， 但是调用存储过程失败!!!!!严重错误:" + JSON.toJSON(item) + "------"
						+ "此订单成功后，手工操作对于收款方金额加操作！！！");
				item.setOrderStatus(OrderStatus.InProcess.getValue());
				item.setRespCode(Resp.InProcess.getCode());
				item.setRespMsg(Resp.InProcess.getMsg());
				renderFail("订单:" + item.getOrderNo() +"提现(付款)失败:尽快联系技术人员处理!!!!!" + resp.getRespMsg());
			}
			item.update();
		}

		if (BizType.DF_Company.getValue().equals(item.getBizType())
				|| BizType.DF_Personal.getValue().equals(item.getBizType())
				|| BizType.Withdraw_Company.getValue().equals(item.getBizType())
				|| BizType.Withdraw_Personal.getValue().equals(item.getBizType())) {

			item.setOrderStatus(OrderStatus.Success.getValue());
			item.setRespCode(Resp.Success.getCode());
			item.setRespMsg(Resp.Success.getMsg());
			item.setPayTime(ZODate.getDateTime());
			item.setSettleDate(ZODate.getDate());
			// TODO 把订单发送到付款渠道
			log.info("订单" + item.getOrderNo() + "发往渠道" + item.getChannelCode());
			item.update();
			renderSuccess("提现(付款)提交成功");
		}

		if (OrderStatus.Success.getValue().equals(item.getOrderStatus())) {

			try {
				createCertificate(item.getId());
			}catch (Exception e){e.printStackTrace();}

			MerchUser user = MerchUser.dao.selectByMerCode(item.getMerchCode());
			if (user == null) {
				return;
			}
			long realAmt = Math.abs(item.getAmount()) + item.getFee();// 钱包总支出的金额
			WalletSMS.sendSMSSubMenoy(user.getUserName(), realAmt , item.getBalance());
		}

	}


	@Before(Tx.class)
	public void toTransferOutList(){
		String res = getPara("num");
		String orderList = getPara("orderNoList");
		ZOLog.api.info("收到批量处理打款数据:"+ res + "---" + orderList);

		int num = Integer.parseInt(res);
		String[] orderNoStr = orderList.split(";");

		List<TradeOrder> tradeOrderList = new ArrayList<> ();
		for(int i = 0; i < num; i++){
			TradeOrder tradeOrder = TradeOrder.dao.selectByOrderNo(orderNoStr[i]);
			if(tradeOrder == null){
				renderFail("订单号:" + orderNoStr[i] + "不存在!!");
				return;
			}
			if (BizType.DF_Company.getValue().equals(tradeOrder.getBizType())
					|| BizType.DF_Personal.getValue().equals(tradeOrder.getBizType())
					|| BizType.Withdraw_Company.getValue().equals(tradeOrder.getBizType())
					|| BizType.Withdraw_Personal.getValue().equals(tradeOrder.getBizType())){
				tradeOrderList.add(tradeOrder);
			}else {
				renderFail("订单号:" + orderNoStr[i] + "不属于对公或者对私转账，钱包内转账不能批量操作!");
				return;
			}
		}
		StringBuffer resp = new StringBuffer();

		for(TradeOrder item: tradeOrderList){
			item.setOrderStatus(OrderStatus.Success.getValue());
			item.setRespCode(Resp.Success.getCode());
			item.setRespMsg(Resp.Success.getMsg());
			item.setPayTime(ZODate.getDateTime());
			item.setSettleDate(ZODate.getDate());
			// TODO 把订单发送到付款渠道
			log.info("订单" + item.getOrderNo() + "发往渠道" + item.getChannelCode());
			item.update();
			resp.append("订单:" + item.getOrderNo() + "付款成功<br>");

			MerchUser user = MerchUser.dao.selectByMerCode(item.getMerchCode());
			if(user!=null) {
				long realAmt = Math.abs(item.getAmount()) + item.getFee();// 钱包总支出的金额
				WalletSMS.sendSMSSubMenoy(user.getUserName(), realAmt, item.getBalance());
			}

			try {
				createCertificate(item.getId());
			}catch (Exception e){e.printStackTrace();}

		}
		renderSuccess(resp.toString());
	}

	/** 展示电子回单图形 */
	public void certificate() throws Exception {
		File file = new File(SystemConfig.config.get("file_center_path") + "certificate/" + getPara("id") + ".jpg");
		if (file.exists()) {
			renderFile(file);
		} else {
			TradeOrder order = TradeOrder.dao.findById(getPara("id"));
			BufferedImage image = Certificate.createImage(order);
			FileOutputStream fos = new FileOutputStream(file);
			ImageIO.write(image, "jpeg", fos);
			fos.close();
			renderFile(file);
		}
	}



	private void createCertificate(String id) throws Exception {
		File file = new File(SystemConfig.config.get("file_center_path") + "certificate/" + id + ".jpg");
		if (file.exists()) {

		} else {
			TradeOrder order = TradeOrder.dao.findById((id));
			BufferedImage image = Certificate.createImage(order);
			FileOutputStream fos = new FileOutputStream(file);
			ImageIO.write(image, "jpeg", fos);
			fos.close();
		}
	}


	public void report() throws Exception{
		List<Dictionary> payTypeList = Dictionary.dao.selectBizType();
		Map<String, String> payTypeMap = new HashMap<>();
		for (Dictionary payType : payTypeList) {
			payTypeMap.put(payType.getCode(), payType.getName());
		}
		Map<String, String> orderStatus = new HashMap<>();
		for (OrderStatus os : OrderStatus.values()) {
			orderStatus.put(os.getValue(), os.getName());
		}

		ZOSearchCondition sc = super.getSearchCondition();

		sc.put("orderStatus", OrderStatus.WaitTransferOut.getValue());//只需要导出待打款的。
		String fileName = "pay" + ZODate.getDateTime().replace(":", "-");
		String templatePath = SystemEnum.FilePath.ReportTemplate.getValue() + "pay_trade_details.xlsx";
		String targetPath = SystemEnum.FilePath.ReportTmp.getValue() + fileName + ".xlsx";
		LinkedHashMap<String, Context> sheetNameAndData = new LinkedHashMap<>();
		int loop = 2; //SystemEnum.BizType.values().length;
		String[] templateSheetName = new String[loop];
		for(int i = 0; i < loop; i++){
			int sheetIndex = i + 1;
			templateSheetName[i] = "Sheet" + sheetIndex;
		}
		Map<String, Object> data = new HashMap<>();
		//循环遍历交易类型
		List<TradeOrder> orderNoList = new ArrayList<>();
		for(int t = 0; t < 2; t++) {
			String name = "";
			if(t == 0){
				name = "对私待打款";
				sc.put("bizType", BizType.Withdraw_Personal.getValue());
				sc.put("bizType2", BizType.DF_Personal.getValue());//导出一种交易类型
			}else if(t == 1) {
				name = "对公待打款";
				sc.put("bizType", BizType.Withdraw_Company.getValue());
				sc.put("bizType2", BizType.DF_Company.getValue());//导出一种交易类型
			}
			List<TradeOrder> items = TradeOrder.dao.searchReportForAdmin(sc);

			for (TradeOrder item : items) {
				orderNoList.add(item);
				item.setOrderStatus(orderStatus.get(item.getOrderStatus()));
			}
			Context context = new Context();
			context.putVar("list", items);
			sheetNameAndData.put(name, context);
		}
		ZOExcel.exportLargeData(templatePath, targetPath, sheetNameAndData, templateSheetName);
		data.put("orderList" , orderNoList);
		getSession().setAttribute("orderList" , orderNoList);
		renderSuccess("/upload/report/tmp/" + fileName + ".xlsx", data);
	}

	//等待付款的 表格数据
	public void tableWT(){
		@SuppressWarnings("unchecked")
		List<TradeOrder> orderNoList  =  (List<TradeOrder>) getSession().getAttribute("orderList");
		setAttr("orderList", orderNoList);
		List<String> orderStrList = new ArrayList<> ();
		for(TradeOrder tradeOrder: orderNoList){
			orderStrList.add(tradeOrder.getOrderNo());
		}
		setAttr("jsonList", JSON.toJSONString(orderStrList));
		render("trade/payOrderTable.html");
	}

	//暂存户转出--转账到银行卡
	public void payBankPage(){
		setAttr("tempAccountList", Account.dao.find("select * from account WHERE temp = true"));
		render("trade/payTempBankPage.html");
	}

	// 暂存户转出--转账到钱包
	public void payWalltPage(){
		setAttr("tempAccountList", Account.dao.find("select * from account WHERE temp = true"));
		render("trade/payTempWalletPage.html");
	}

	public void payWalletTemp(){
		TradeOrder tradeOrder = getModel(TradeOrder.class);
		Account ac = Account.dao.select(tradeOrder.getMerchCode());
		if (ac == null) {
			renderFail("暂存户付款提交失败,未找到商户对应的虚账账户");
			return;
		}

		String InAccountNo =  getPara("accountNo");
		tradeOrder.setMerchName(ac.getAccountName());
		tradeOrder.setOutAccountNo(ac.getAccountNo());
		tradeOrder.setOutAccountName(ac.getAccountName());
		tradeOrder.setOutBankName("暂存户");

		BigDecimal amount = new BigDecimal(getPara("amount")).multiply(new BigDecimal(100));
		tradeOrder.setId(ZOIDGenerate.getUUID());
		tradeOrder.setChannelCode("temp");
		tradeOrder.setOrderNo(ZOIDGenerate.getSixOrderNo());
		tradeOrder.setOutOrderNo(tradeOrder.getOrderNo());
		tradeOrder.setFee(0L);
		tradeOrder.setAmount(-amount.longValue());

		AccountBalanceChangeResp resp = accountService.subMoney(ac.getAccountNo(), (amount.longValue()));
		if(!"SUCCESS".equals(resp.getRespCode())){
			renderFail("暂存户钱包余额不足!" + ac.getAccountName() + ac.getAccountNo());
			return;
		}
		tradeOrder.setBalance(Long.parseLong(resp.getBalance()));

		tradeOrder.setOrderStatus(OrderStatus.FirstReview.getValue());
		tradeOrder.setCreateTime(ZODate.getDateTime());

		tradeOrder.setBizType(BizType.TransferOut.getValue());
//		tradeOrder.setBalance();
		//入账账户
		tradeOrder.setAccountName(getPara("accountName"));
		tradeOrder.setAccountNo(InAccountNo);

		tradeOrder.save();
		renderSuccess(tradeOrder.getOrderNo());
	}

	/**
	 * 设置订单为待打款状态
	 */
	private void setOrderTransferOut(TradeOrder order, String RespMsg) {
		order.setOrderStatus(OrderStatus.WaitTransferOut.getValue());
		order.setRespCode(Resp.Success.getCode());
		order.setRespMsg(RespMsg);
		order.update();
	}
}
